import { useEffect } from 'react';
import OHIF from '@ohif/core';
import { useSelector } from 'react-redux';

const { StudyPrefetcher } = OHIF.classes;

const StudyPrefetcherComponent = ({ studies, currentStudyIndex }) => {
  const studyPrefetcher = StudyPrefetcher.getInstance();

  const activeDisplaySetUID = useSelector(state => {
    const modeState = state.viewports[state.viewports.viewMode];
    const index = modeState.activeViewportIndex;
    const data = modeState.viewportSpecificData;
    return data[index] ? data[index].displaySetInstanceUID : null;
  });

  useEffect(() => {
    if (studies.length <= currentStudyIndex) return;

    const displaySets = studies[currentStudyIndex].displaySets || [];

    const activeDisplaySet = displaySets.find(
      ds => ds.displaySetInstanceUID === activeDisplaySetUID
    );

    studyPrefetcher.setDisplaySets(displaySets, activeDisplaySet);
    studyPrefetcher.prefetch();

    return () => { studyPrefetcher.destroy(); }
  }, [studies, activeDisplaySetUID, currentStudyIndex]);

  return null;
}

export default StudyPrefetcherComponent;
